import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useFavoriteStore = defineStore('favorite', () => {
  const favorites = ref([])
  const loading = ref(false)

  // 获取收藏列表
  const fetchFavorites = async () => {
    loading.value = true
    try {
      // 模拟API调用
      favorites.value = [
        {
          id: 1,
          postId: 101,
          title: 'Vue3 组合式API最佳实践',
          author: '技术达人',
          content: 'Vue3的组合式API（Composition API）提供了更好的代码组织方式...',
          createTime: '2024-03-20',
          favoriteTime: '2024-03-21',
          views: 1580,
          likes: 234,
          comments: 45,
          category: '技术交流'
        },
        {
          id: 2,
          postId: 102,
          title: '前端性能优化实战指南',
          author: '性能专家',
          content: '本文将从多个角度介绍前端性能优化的实用技巧...',
          createTime: '2024-03-19',
          favoriteTime: '2024-03-20',
          views: 2340,
          likes: 567,
          comments: 89,
          category: '技术分享'
        },
        {
          id: 3,
          postId: 103,
          title: '响应式设计与移动端适配',
          author: 'UI专家',
          content: '如何打造完美的移动端用户体验？本文将为您详细解答...',
          createTime: '2024-03-18',
          favoriteTime: '2024-03-19',
          views: 1890,
          likes: 345,
          comments: 67,
          category: '前端开发'
        }
      ]
    } catch (error) {
      console.error('获取收藏列表失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 添加收藏
  const addFavorite = async (post) => {
    try {
      // 模拟API调用
      const favorite = {
        id: favorites.value.length + 1,
        postId: post.id,
        title: post.title,
        author: post.author,
        content: post.content,
        createTime: post.createTime,
        favoriteTime: new Date().toISOString().split('T')[0],
        views: post.views,
        likes: post.likes,
        comments: post.comments,
        category: post.category
      }
      favorites.value.unshift(favorite)
      return true
    } catch (error) {
      console.error('添加收藏失败:', error)
      return false
    }
  }

  // 取消收藏
  const removeFavorite = async (favoriteId) => {
    try {
      // 模拟API调用
      favorites.value = favorites.value.filter(f => f.id !== favoriteId)
      return true
    } catch (error) {
      console.error('取消收藏失败:', error)
      return false
    }
  }

  // 检查是否已收藏
  const isFavorited = (postId) => {
    return favorites.value.some(f => f.postId === postId)
  }

  return {
    favorites,
    loading,
    fetchFavorites,
    addFavorite,
    removeFavorite,
    isFavorited
  }
}) 